import Vue from 'vue'
// Lib imports
import axios from 'axios'
import iziToast from "./toast/izitoast";
import VueCookie from "vue-cookie";
import router from "../router";


/****** 全局统一处理 request 拦截器 ******/
axios.interceptors.request.use(
    config => {
        let access_token = VueCookie.get("echo_access_token");
        if (access_token && config.method !== 'get') {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = `bearer ` + access_token;
        }
        return config;
    },
    err => {
        if (err.response) {
            VueCookie.delete('echo_access_token');
            VueCookie.delete('echo_refresh_token');
            switch (err.response.status) {
                case 401:
                    router.replace({
                        path: '/login',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    });
                    break;
                case 500:
                    router.replace({
                        path: '/login',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    });
                    break;
            }
        }
        return Promise.reject(err);
    }
);

/****** 全局统一处理 response 拦截器******/
axios.interceptors.response.use(
    response => {
        //这里根据后端提供的数据进行对应的处理
        if (response.data.success) {
            return response;
        } else {
            //常规错误处理
            console.log("全局拦截常规的错误如下:" + response.data.message);
            return response;
        }
    },
    error => {
        //响应错误处理
        let res = error.response;
        let responseData = res.data;
        let responseStatus = res.status;
        if (responseStatus === 401) {
            //当前页面有资源未授权则打印出来，然后返回首页
            console.log("此路径资源位授权：" + res.config.url);
            iziToast.error({message: "先登录再操作好吗,宝贝?", position: "topCenter"});
            router.push("/parallax");

        }
        return Promise.reject(error)
    }
);

Vue.prototype.$axios = axios;
